<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        position: absolute;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <button id="btn200">到200</button>
    <button id="btn400">到400</button>
    <button id="btn800">到800</button>
    <hr />
    <div id="box"></div>
    <script>
      var btn200 = document.querySelector("#btn200");
      var btn400 = document.querySelector("#btn400");
      var btn800 = document.querySelector("#btn800");
      var box = document.querySelector("#box");

      btn200.addEventListener("click", function () {
        animate(box, 200);
      });

      btn400.addEventListener("click", function () {
        animate(box, 400);
      });

      btn800.addEventListener("click", function () {
        animate(box, 800);
      });

      //   运动函数：1.需要让谁移动  2.移动到哪里
      function animate(obj, target, callback) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          // 获取盒子的位置
          var currentPos = obj.offsetLeft;
          // 步长值
          var step = (target - currentPos) / 10;
          step = step > 0 ? Math.ceil(step) : Math.floor(step);
          // 限制盒子的移动距离
          if (currentPos === target) {
            callback && callback();
            clearInterval(obj.timer);
            return;
          }

          obj.style.left = currentPos + step + "px";
        }, 15);
      }
    </script>
  </body>
</html>
